﻿Imports System
Imports System.Windows.Forms
Imports IceChat
Imports IceChatPlugin
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Runtime.InteropServices

Public Class Plugin
    Inherits IPluginIceChat

    Public Overrides ReadOnly Property Author As String
        Get
            Return "George W Bush"
        End Get
    End Property
    Public Overrides ReadOnly Property Name As String
        Get
            Return "DoxBot Plug-in"
        End Get
    End Property
    Public Overrides ReadOnly Property Version As String
        Get
            Return "1.0"
        End Get
    End Property

    Public Shadows Event OnCommand As OutGoingCommandHandler
    Private WithEvents pToggleDoxBot As ToolStripMenuItem
    Private pBotChannels As Hashtable

    <DllImport("Kernel32.dll", SetLastError:=True)> _
    Public Shared Function AllocConsole() As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True)> _
    Public Shared Function FreeConsole() As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    Private Const colorChar As Char = Chr(3)
    Private Const underlineChar As Char = Chr(31)
    Private Const boldChar As Char = Chr(2)
    Private Const plainChar As Char = Chr(15)
    Private Const reverseChar As Char = Chr(22)
    Private Const italicChar As Char = Chr(29)

    Private Structure sBotChan
        Public Connection As IceChat.IRCConnection
        Public Channel As String
        Public IgnoreUsers As List(Of String)
        Sub New(ByVal Con As IceChat.IRCConnection, ByVal Chan As String)
            Connection = Con
            Channel = Chan
            IgnoreUsers = New List(Of String)
        End Sub
    End Structure

    Public Overrides Sub Dispose()
        FreeConsole()
    End Sub

    Public Overrides Sub Initialize()
        pBotChannels = New Hashtable
        pToggleDoxBot = New ToolStripMenuItem
        With pToggleDoxBot
            .Text = "Toggle DoxBot"
            .Checked = False
            .Name = "mnuEnableDoxBot"
        End With
        If Not AllocConsole() Then
            MsgBox(Marshal.GetLastWin32Error)
        End If
    End Sub

    Public Overrides Function AddChannelPopups() As System.Windows.Forms.ToolStripItem()
        Return (New System.Windows.Forms.ToolStripItem() {pToggleDoxBot})
    End Function

    Private Sub pToggleDoxBot_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pToggleDoxBot.Click
        Dim Key As String = ServerTreeCurrentConnection.ServerSetting.ServerName & ":" & ServerTreeCurrentConnection.ServerSetting.NickName & ":" & ServerTreeCurrentTab
        Console.WriteLine("Toggle: " & Key)
        If Not pBotChannels.Contains(Key) Then
            pBotChannels.Add(Key, New sBotChan(ServerTreeCurrentConnection, ServerTreeCurrentTab))
            SendEcho(ServerTreeCurrentConnection, "DoxBot is now Enabled on " & ServerTreeCurrentTab & ".")
        Else
            pBotChannels.Remove(Key)
            SendEcho(ServerTreeCurrentConnection, "DoxBot is now Disabled on " & ServerTreeCurrentTab & ".")
        End If
    End Sub

    Public Overrides Function ChannelMessage(ByVal args As PluginArgs) As PluginArgs
        Dim Key As String = args.Connection.ServerSetting.ServerName & ":" & args.Connection.ServerSetting.NickName & ":" & args.Channel
        Dim Message As String = StripColorCodes(args.Message)
        Message = Right(Message, Len(Message) - (Len(args.Nick) + 4))
        Console.WriteLine("ChannelMessage: " & Message)
        If pBotChannels.Contains(Key) Then
            ' Check if it is a command
            If Left(Message, 1) = "$" Then
                Console.WriteLine("This is a command")
                HandleCommand(UCase(Trim(Right(Message, Len(Message) - 1))), args.Connection, args.Nick)
            End If
        Else
            SendEcho(args.Connection, "DoxBot is not enabled on this channel.")
        End If
        Return MyBase.ChannelMessage(args)
    End Function

    Public Overrides Function InputText(ByVal args As PluginArgs) As PluginArgs
        Dim Key As String = args.Connection.ServerSetting.ServerName & ":" & args.Connection.ServerSetting.NickName & ":" & ServerTreeCurrentTab
        Console.WriteLine("InputText: " & args.Command)
        If pBotChannels.Contains(Key) Then
            If Left(args.Command, 1) = "$" Then
                Console.WriteLine("This is a command")
                HandleCommand(UCase(Trim(Right(args.Command, Len(args.Command) - 1))), args.Connection, args.Connection.ServerSetting.NickName)
            End If
        End If
        Return MyBase.InputText(args)
    End Function

    Private Sub SendMessage(ByVal Connection As IRCConnection, ByVal Recipient As String, ByVal Message As String)
        SendCommand(Connection, "/msg " & Recipient & " " & Message)
    End Sub

    Private Sub SendEcho(ByVal Connection As IRCConnection, ByVal Message As String)
        SendCommand(Connection, "/echo " & Message)
    End Sub

    Private Function StripColorCodes(ByVal line As String) As String
        Dim ParseBackColor As String = "\x03([0-9]{1,2}),([0-9]{1,2})"
        Dim ParseForeColor As String = "\x03[0-9]{1,2}"
        Dim ParseColorChar As String = "\x03"
        Dim ParseBoldChar As String = "\x02"
        Dim ParseUnderlineChar As String = "\x1F"
        Dim ParseReverseChar As String = "\x16"
        Dim ParseItalicChar As String = "\x1D"
        line = line.Replace("&#x3;", colorChar.ToString())
        Dim sLine As New StringBuilder()
        sLine.Append(line)
        Dim ParseIRCCodes As New Regex(ParseBackColor & "|" & ParseForeColor & "|" & ParseColorChar & "|" & ParseBoldChar & "|" & ParseUnderlineChar & "|" & ParseReverseChar & "|" & ParseItalicChar)
        Dim m As Match = ParseIRCCodes.Match(sLine.ToString())
        While m.Success
            sLine.Remove(m.Index, m.Length)
            m = ParseIRCCodes.Match(sLine.ToString(), m.Index)
        End While
        Return sLine.ToString()
    End Function

    Private Sub HandleCommand(ByVal Command As String, ByVal Connection As IRCConnection, ByVal Who As String)

        Console.WriteLine("HandleCommand: " & Command)

        Select Case Command

            Case "HELP"

                SendMessage(Connection, Who, "DoxBotPlugin Help:")

        End Select

    End Sub

End Class

